package indi.mozping.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import indi.mozping.bean.QueryParamsBean;
import indi.mozping.service.QueryService;
import indi.mozping.utils.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;

/**
 * @author by mozping
 * @Classname QueryController
 * @Description TODO
 * 查询条件：时间+两个id（一般为in，in里面id数量不超过1000）；
 * * 一般操作为并发1000插入时查询性能和插入性能；
 * @Date 2019/2/22 13:48
 */
@RestController
@RequestMapping("/query")
public class QueryController {


    @Autowired
    QueryService queryService;

    @PostMapping
    public JSONObject query(@RequestBody JSONObject param) {

        QueryParamsBean queryParamsBean = new QueryParamsBean();


        if (param.containsKey("table")) {
            String table = param.getString("table");
            queryParamsBean.setTable(table);
        } else {
            return Util.getFail("请求参数不包含表名称!");
        }

        if (param == null || param.isEmpty()) {
            return Util.getFail("参数不能为空!");
        }

        if (param.containsKey("where")) {
            JSONObject where = param.getJSONObject("where");
            queryParamsBean.setWhere(where);
        }

        if (param.containsKey("in")) {
            JSONObject in = param.getJSONObject("in");
            queryParamsBean.setIn(in);
        }
        if (param.containsKey("eq")) {
            JSONArray eq = param.getJSONArray("eq");
            queryParamsBean.setEq(eq);
        }
        if (param.containsKey("like")) {
            JSONArray like = param.getJSONArray("like");
            queryParamsBean.setLike(like);
        }
        if (param.containsKey("pageParam")) {
            JSONObject pageParam = param.getJSONObject("pageParam");
            queryParamsBean.setPageParam(pageParam);
        }

        if (param.containsKey("sort")) {
            JSONObject sort = param.getJSONObject("sort");
            queryParamsBean.setSort(sort);
        }

        JSONArray queryResult;
        try {
            queryResult = queryService.query(queryParamsBean);
        } catch (ParseException e) {
            e.printStackTrace();
            return Util.getFail("查询数据过程中出现异常" + e.getMessage());
        }

        JSONObject ret = Util.getSuccess();
        ret.put("date", queryResult);
        return ret;
    }

}
